package com.drxx.controller;

import com.drxx.bean.ErrorBean;
import com.drxx.bean.UserInfo;
import com.drxx.dto.Todo;
import com.drxx.dto.TodoDTO;
import com.drxx.service.IUserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.Locale;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.drxx.bean.UserInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
 * @author Petri Kainulainen
 */
@Controller
@SessionAttributes("todo")
public class TodoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TodoController.class);

    protected static final String FEEDBACK_MESSAGE_KEY_TODO_DELETED = "feedback.message.todo.deleted";
    protected static final String FLASH_MESSAGE_KEY_FEEDBACK = "feedbackMessage";

    protected static final String MODEL_ATTRIBUTE_TODO = "todo";


    protected static final String REQUEST_MAPPING_TODO_LIST = "/";

    protected static final String VIEW_TODO_ADD = "todo/add";


    @Autowired
    private  IUserInfoService service;

    @Autowired
    private  MessageSource messageSource;

    @ResponseBody
    @RequestMapping(value = "/rest/{ownerId}.do", method = RequestMethod.GET)
    public String findOwner(@PathVariable String ownerId, Model model) {
        return ownerId;
    }

    @ResponseBody
    @RequestMapping(value = "/todo/test", method = RequestMethod.GET)
    public String testa(Model model, HttpServletResponse rep)
            throws IOException {
        model.addAttribute("abc", "efd");
        UserInfo userInfo = new UserInfo();
        model.addAttribute(userInfo);
        return "Hello World";
    }

    @ResponseBody
    // 理论上可以@ResponseBody 支持直接返回teacher对象 但是3.2里有问题 我们还是老实返回字符串吧
    @RequestMapping(value = "/testb.do", method = RequestMethod.GET)
    public String testb(Model model, HttpServletResponse rep,
                        HttpServletRequest req, String ex) throws IOException {
        // WEB中获得SPRING容器
        WebApplicationContext wac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(req.getServletContext());
        Gson gson = new Gson();
        return  gson.toJson(wac.getBean(UserInfo.class));
    }

    @ResponseBody
    @RequestMapping(value = "/post.do", method = RequestMethod.POST)
    public String post(Model model, HttpServletResponse rep,
                       HttpServletRequest req, String ex) throws IOException {

        Gson gson = new Gson();
        return gson.toJson(req.getParameterMap());
    }


    @ResponseBody
    @RequestMapping(value = "/todo/add", method = RequestMethod.GET)
    public String showAddTodoForm(Model model) {

        LOGGER.debug("Rendering showAddTodoForm to-do entry form.");

        UserInfo formObject = new UserInfo();
        formObject.setName("王小二");
        model.addAttribute(MODEL_ATTRIBUTE_TODO, formObject);
        return VIEW_TODO_ADD;
    }

    @RequestMapping(value = "/todo/add", method = RequestMethod.POST)
    public String add(Model model) {
        LOGGER.debug("Rendering add to-do entry form.");

        TodoDTO formObject = new TodoDTO();
        formObject.setDescription("description");
        formObject.setTitle("title");
        model.addAttribute(MODEL_ATTRIBUTE_TODO, formObject);
        return VIEW_TODO_ADD;
    }

    @RequestMapping(value = "/todo/delete/{id}", method = RequestMethod.GET)
    public String deleteById(@PathVariable("id") Integer id, RedirectAttributes attributes) {
        LOGGER.debug("Deleting a to-do entry with id: {}", id);

        UserInfo deleted = service.deleteById(id);
        LOGGER.debug("Deleted to-do entry with information: {}", deleted);

        addFeedbackMessage(attributes, FEEDBACK_MESSAGE_KEY_TODO_DELETED, deleted.getName());

        return createRedirectViewPath(REQUEST_MAPPING_TODO_LIST);
    }

    private void addFeedbackMessage(RedirectAttributes attributes, String messageCode, Object... messageParameters) {
        LOGGER.debug("Adding feedback message with code: {} and params: {}", messageCode, messageParameters);
        String localizedFeedbackMessage = getMessage(messageCode, messageParameters);
        LOGGER.debug("Localized message is: {}", localizedFeedbackMessage);
        attributes.addFlashAttribute(FLASH_MESSAGE_KEY_FEEDBACK, localizedFeedbackMessage);
    }

    private String getMessage(String messageCode, Object... messageParameters) {
        Locale current = LocaleContextHolder.getLocale();
        LOGGER.debug("Current locale is {}", current);
        return messageSource.getMessage(messageCode, messageParameters, current);
    }


    private String createRedirectViewPath(String requestMapping) {
        StringBuilder redirectViewPath = new StringBuilder();
        redirectViewPath.append("redirect:");
        redirectViewPath.append(requestMapping);
        return redirectViewPath.toString();
    }
}
